package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.StoreInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.DataManager;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IYetLayMenFg;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.AddMenDianActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.CdbListInfoActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.MenDianActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.YetAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseFragmentActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseFragmentPresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.CharacterParser;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DialogUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ZhangfenComparator;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SelectPicPopupWindow;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SimpleDialog;

import org.greenrobot.eventbus.EventBus;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

import static android.R.attr.id;

/**
 * 作者：Administrator on 2017/6/20 11:59
 * 邮箱：zhanghuaiha@gmail.com
 */

public class YetLayMenPresenter extends BaseFragmentPresenter<IYetLayMenFg> {

    private YetAdapter adapter;
    private MenDianActivity menDianActivity;
    private SelectPicPopupWindow menuWindow;
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private String udid;
    private String eid;
    private String versionName;
    private SimpleDialog selfDialog;
    private RecyclerView recycler;
    private LinearLayoutManager linearLayoutManager;
    private StoreInfo store;
    private int cont = 1;
    private EditText search;
    private List<StoreInfo.DataBean> data;
    private CharacterParser characterParser;
    private String name;
    private Dialog dialog;
    private String location;
    private Dialog selectDialog;
    private ZhangfenComparator zhangfenComparator;
    private List<StoreInfo.DataBean> wifi;
    private List<StoreInfo.DataBean> mima;
    private List<StoreInfo.DataBean> paper;
    private List<StoreInfo.DataBean> data_num;
    private int total = -1;
    private int wifi_num = -1;
    private int mima_num = -1;
    private int num = -1;
    private int paper_num = -1;
    private String type = "0";

    public YetLayMenPresenter(BaseFragmentActivity context) {
        super(context);

    }

    public void loadContacts() {
        manager = new DataManager(mContext);
        mCompositeSubscription = new CompositeSubscription();
        menDianActivity = getView().getMDActivity();
        recycler = getView().getRecycler();
        search = getView().getSearch();
        linearLayoutManager = new LinearLayoutManager(mContext);
        recycler.setLayoutManager(linearLayoutManager);
        udid = App.SP.getString("udid", "");
        eid = App.SP.getString("id", "");
        zhangfenComparator = new ZhangfenComparator();
        versionName = ObtainVersion.getVersionName(mContext);

        if (data_num == null) {
            data_num = new ArrayList<StoreInfo.DataBean>();
        } else {
            data_num.clear();
        }

        if (wifi == null) {
            wifi = new ArrayList<StoreInfo.DataBean>();
        } else {
            wifi.clear();
        }

        if (mima == null) {
            mima = new ArrayList<StoreInfo.DataBean>();
        } else {
            mima.clear();
        }

        if (paper == null) {
            paper = new ArrayList<StoreInfo.DataBean>();
        } else {
            paper.clear();
        }

        setAdapter();
        loadData();


        //加载更多
        recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastVisiblePosition = linearLayoutManager.findLastVisibleItemPosition();
                    if (lastVisiblePosition >= linearLayoutManager.getItemCount() - 1) {
                        if (total < 20) {
                            return;
                        } else {
                            getDataInfo(type);
                        }
                    }
                }
            }
        });

    }

//    public void searh(String tv, List<StoreInfo.DataBean> list) {
//        List<StoreInfo.DataBean> filterDateList = new ArrayList<>();
//        if (tv.equals("取消")) {
//            search.setText("");
//            filterDateList = list;
//        } else {
//            String s = search.getText().toString().trim();
//            if (TextUtils.isEmpty(s)) {
//                filterDateList = list;
//            } else {
//                if (!list.contains(s)) {
//                    filterDateList.clear();
//                    for (StoreInfo.DataBean info : list) {
//                        name = info.getName();
//                        location = info.getSpecific_address();
//                        if (name.indexOf(s) != -1 || location.indexOf(s) != -1) {
//                            int i = name.indexOf(s);
//                            System.out.println(i);
//                            filterDateList.add(info);
//                        }
//                    }
//                }
//            }
//        }
//
//        adapter.addData(filterDateList);
//    }

    public void unLoadData() {
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    private void setAdapter() {
        if (adapter == null) {
            adapter = new YetAdapter(mContext);
        }
        recycler.setAdapter(adapter);
        adapter.setItemClickListenter((dataBean, position) -> selectImgs(dataBean, position, dataBean.getId()));
    }


    public void loadData() {
        getDataInfo("0");
    }

//    public List<StoreInfo.DataBean> getDate(String type) {
//        if (type.equals("4")) {
//            return mima;
//        } else if (type.equals("1")) {
//            return wifi;
//        } else if (type.equals("5")) {
//            return paper;
//        } else {
//            return data;
//        }
//    }

//    public void getWifi(String type) {
//        if (type.equals("4")) {
//            adapter.addData(mima);
//        } else if (type.equals("1")) {
//            adapter.addData(wifi);
//        } else if (type.equals("5")) {
//            adapter.addData(paper);
//        } else {
//            adapter.addData(data);
//        }
//    }

    public int isType(String type) {
        if (type.equals("4")) {
            mima_num++;
            return mima_num;
        } else if (type.equals("1")) {
            wifi_num++;
            return wifi_num;
        } else if (type.equals("5")) {
            paper_num++;
            return paper_num;
        } else {
            num++;
            return num;
        }
    }

    public void isTypeList(List<StoreInfo.DataBean> data) {
        if (type.equals("4")) {
            mima.addAll(data);
            adapter.addData(mima);
        } else if (type.equals("1")) {
            wifi.addAll(data);
            adapter.addData(wifi);
        } else if (type.equals("5")) {
            paper.addAll(data);
            adapter.addData(paper);
        } else {
            data_num.addAll(data);
            adapter.addData(data_num);
        }
    }

    public void getDataInfo(String type) {
        TSDialog();
        this.type = type;
        int index = isType(type);
        String tiem = System.currentTimeMillis() + "";
        Map<String, String> map = new LinkedHashMap<>();
        map.put("rf", "2");
        map.put("ts", tiem);
        map.put("v", versionName);
        map.put("i", NetWorkCodeInfo.STORE);
        map.put("udid", udid);
        map.put("eid", eid);
        map.put("page_size", "20");
        map.put("page_index", index+"");
        map.put("status", "1");
        if (!type.equals("0")) {
            map.put("store_type", type);
        }

        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry", encry1);
        RetrofitFactory.getmInstanse().mApi.getStoreInfo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<StoreInfo>() {
                    @Override
                    public void success(StoreInfo storeInfo) {
                        if (storeInfo.getCode() == 200) {
                            total = Integer.parseInt(storeInfo.getTotal());

                            store = storeInfo;
                            data = storeInfo.getData();
                            isTypeList(data);


//                            for (StoreInfo.DataBean dataBean : data) {
//                                if (dataBean.getStore_type().equals("1")) {
//                                    wifi.add(dataBean);
//                                }else if (dataBean.getStore_type().equals("4")) {
//                                    mima.add(dataBean);
//                                }else if (dataBean.getStore_type().equals("5")) {
//                                    paper.add(dataBean);
//                                }else {
//                                    wifi.add(dataBean);
//                                }
//                            }
                        }
                        dialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dialog.dismiss();
                    }
                });
    }


    public void search(String name) {
        TSDialog();
        String tiem = System.currentTimeMillis() + "";
        Map<String, String> map = new LinkedHashMap<>();
        map.put("rf", "2");
        map.put("ts", tiem);
        map.put("v", versionName);
        map.put("i", NetWorkCodeInfo.STORE);
        map.put("udid", udid);
        map.put("eid", eid);
        map.put("status", "1");
        map.put("page_size", "20");
        map.put("page_index","0");
        map.put("name", name);
        if (!type.equals("0")) {
            map.put("store_type", type);
        }
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry", encry1);
        RetrofitFactory.getmInstanse().mApi.getStoreInfo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<StoreInfo>() {
                    @Override
                    public void success(StoreInfo storeInfo) {
                        store = storeInfo;
                        data = storeInfo.getData();
                        adapter.addData(data);
                        dialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dialog.dismiss();
                    }
                });
    }

    public void TSDialog() {
        dialog = DialogUtils.uploadDialog(mContext, mContext.getString(R.string.upload), true);
    }


    /*
     PopupWindow展示
     */
    private void selectImgs(StoreInfo.DataBean dataBean, int posotion, String id) {

        ((InputMethodManager) menDianActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(menDianActivity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        menuWindow = new SelectPicPopupWindow(menDianActivity) {

            @Override
            public View initView() {
                LayoutInflater inflater = (LayoutInflater) menDianActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View menuview = inflater.inflate(R.layout.item_mendian_popupwindows, null);

                TextView one = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_one);
                TextView two = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_two);
                TextView three = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_three);
                TextView four = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_four);
                TextView end = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_end);
                View heng = menuview.findViewById(R.id.heng);
                three.setText("待铺设");

                /**
                 * 取消按钮销毁事件
                 * by黄海杰@2015-1-7
                 */
                end.setOnClickListener(v -> dismiss());
                //所属设备
                one.setOnClickListener(v -> {
                    Intent intent = new Intent(menDianActivity, CdbListInfoActivity.class);
                    intent.putExtra("sid", id);
                    intent.putExtra("url", dataBean.getImg_url());
                    intent.putExtra("name", dataBean.getName());
                    menDianActivity.jumpToActivity(intent);
                    dismiss();
                });
                //编辑门店
                two.setOnClickListener(v -> {
                    Intent intent = new Intent(menDianActivity, AddMenDianActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("dataBean", dataBean);
                    intent.putExtras(bundle);
                    menDianActivity.startActivity(intent);
                    dismiss();
                });
                //设置为待铺设门店
                three.setOnClickListener(v -> {
                    selectDialog();
                    selectDialog.findViewById(R.id.dialog_save).setOnClickListener(v1 -> {
                        if (dataBean.getAll_num().equals("0")) {
                            setStay(dataBean.getId(), posotion);
                        } else {
                            DialogUtils.TSDialog(mContext, "该店铺下还有设备未撤回,无法设置", true);
                        }
                        selectDialog.dismiss();
                    });
                    dismiss();
                });

                //删除
                four.setOnClickListener(v -> {
//                    delete(id,posotion);
                    Dialog(id, posotion);
                    dismiss();
                });
                return menuview;
            }
        };
        //设置弹窗位置
        menuWindow.showAtLocation(menDianActivity.findViewById(R.id.md), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    private void delete(String id, int posotion) {
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.Delete("2", time, versionName, NetWorkCodeInfo.DELETE, udid, id, eid);
        mCompositeSubscription.add(manager.Delete("2", time, versionName, NetWorkCodeInfo.DELETE, udid, id, eid, encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(codeInt -> {
                    if (codeInt.code == 200) {
                        adapter.deleteItem(posotion);
                        ToastUtil.showToast("删除店铺成功..");
                    } else {
                        ToastUtil.showToast(codeInt.message);
                    }
                }));
    }

    private void Dialog(String id, int posotion) {
        selfDialog = new SimpleDialog(menDianActivity);
        selfDialog.setTitle("提示");
        selfDialog.setMessage("是否删除该记录?");
        selfDialog.setYesOnclickListener("确定", () -> {
            delete(id, posotion);
            selfDialog.dismiss();
        });
        selfDialog.setNoOnclickListener("取消", () -> {
            selfDialog.dismiss();
        });
        selfDialog.show();
    }


    public void setStay(String id, int position) {
        String tiem = System.currentTimeMillis() + "";
        Map<String, String> map = new LinkedHashMap<>();
        map.put("rf", "2");
        map.put("ts", tiem);
        map.put("v", versionName);
        map.put("i", NetWorkCodeInfo.ALREADY_STAY);
        map.put("udid", udid);
        map.put("id", id);
        map.put("eid", eid);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry", encry1);
        RetrofitFactory.getmInstanse().mApi.getStay(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity>() {
                    @Override
                    public void success(BaseResponseEntity baseResponseEntity) {
                        if (baseResponseEntity.code == 200) {
                            adapter.deleteItem(position);
                            EventBus.getDefault().post("update");
                            DialogUtils.TSDialog(mContext, "设置成功", true);
                        } else {
                            DialogUtils.TSDialog(mContext, baseResponseEntity.message, true);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        DialogUtils.TSDialog(mContext, "设置失败，请重试", true);
                    }
                });
    }


    public void selectDialog() {
        selectDialog = DialogUtils.ClickDialog(mContext, "是否将该门店设置为待铺设门店", true);
        selectDialog.findViewById(R.id.dialog_cancel).setVisibility(View.VISIBLE);
        selectDialog.findViewById(R.id.dialog_cancel).setOnClickListener(v -> {
            selectDialog.dismiss();
        });
    }
}
